<section id="college-listing" class="section section-padding-top section-padding-bottom">
	<div class="container" id="filters-area">
		<div class="col">
			<div class="form-row align-items-center">
				<div class="col-md-4">
					<div class="form-group">
						<input type="text" class="form-control" id="input-name-search" placeholder="Search College">
					</div>
				</div>
				<div class="col-md-3">
					<div class="form-group">
						<select name="input-sort" id="input-sort" class="form-control">
							<option value="total_votes" selected># of votes</option>
							<option value="name">College Name</option>
							<option value="location">College Location</option>
						</select>
					</div>
				</div>
				<div class="col-md-3">
					<div class="form-group">
						<select class="form-control" id="input-location-search" name="input-location-search">
							<option value=''>Select Location</option>
							{% for location in frappe.get_all('Location', fields=['name'], order_by="name") %}
									<option>{{ location['name'] }}</option>
							{% endfor %}
						</select>
					</div>
				</div>
				<div class="col-md-2 d-flex flex-row">
					<button id="apply-button" class="btn btn-secondary mr-3 mb-4">Apply</button>
					<button id="clear-button" class="btn btn-default mb-4">Clear</button>
				</div>
			</div>
		</div>
	</div>

	<div class="container colleges">
		<div class="row">
			<main class="col">
				<div class="container-fluid pt-5">
					<div id="college-listings" class="row align-items-stretch">
					</div>
				</div>

				<nav class="d-flex justify-content-center w-100 mt-5" aria-label="Page navigation">
					<button id="load-more-button" class="btn btn-secondary">Load More</button>
				</nav>
			</main>
		</div>
	</div>
</section>

<div class="modal fade" id="social_media_modal" tabindex="-1" role="dialog" aria-labelledby="social_media_modal" aria-hidden="true">
	<div class="modal-dialog" role="document">
		<div class="modal-content col-12">
			<div class="modal-header">
				<h5 class="modal-title">Share</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span> </button>
			</div>
			<div class="modal-body" data-message-title="{{ social_media_title }}" data-message-text="{{ social_media_message }}">
				<div class="icon-container d-flex">
					<div class="social-link">
						<a id="fb">
							<img class="img-social-icon" src="/assets/bhumi_awards_portal/images/facebook.png">
							<p>Facebook</p>
						</a>
					</div>

					<div class="social-link">
						<a id="twitter">
							<img class="img-social-icon" src="/assets/bhumi_awards_portal/images/twitter.png">
							<p>Twitter</p>
						</a>
					</div>

					<div class="social-link">
						<a id="whatsapp">
							<img class="img-social-icon" src="/assets/bhumi_awards_portal/images/whatsapp.png">
							<p>Whatsapp</p>
						</a>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<script>
	// DOM elements
	const collegeListings = document.getElementById("college-listings");
	const loadMoreButton = document.getElementById("load-more-button");
	const applyButton = document.getElementById("apply-button");
	const clearButton = document.getElementById("clear-button");

	// Global variables
	let pageStart = 0;
	let pageLimit = 30;

	let filters = {
		nameQuery: "",
		locationQuery: "",
		sortBy: "total_votes",
		sortOrder: "desc",
	};

	const filterInputs = [
		{ ele: document.getElementById("input-name-search"), key: "nameQuery" },
		{
			ele: document.getElementById("input-location-search"),
			key: "locationQuery",
		},
		{ ele: document.getElementById("input-sort"), key: "sortBy" },
	];

	// Event Listeners
	applyButton.addEventListener("click", () => {
		resetState();
		loadNextPage();
	});

	loadMoreButton.addEventListener("click", (e) => {
		loadNextPage();
	});

	clearButton.addEventListener("click", (e) => {
		window.location.href = "/colleges"
	});

	function loadNextPage() {
		frappe.call({
			method: "bhumi_awards_portal.api.get_colleges",
			args: {
				limit_start: pageStart,
				order_by: `${filters.sortBy} ${filters.sortOrder}`,
				name_query: filters.nameQuery,
				location_query: filters.locationQuery,
			},
			freeze: true,
			callback: ({ message }) => {
				appendToListings(message);
				showShareButtons();
			},
		});
		pageStart += pageLimit;
	}

	function appendToListings(collegeList) {
		if (collegeList.length === 0 || collegeList.length < pageLimit) {
			toggleLoadButton(true);
		}

		let cardHTML = "";
		let abbr = undefined;

		for (let college of collegeList) {
			const redirectPayload = new URLSearchParams({
				"redirect-to": "/vote?new=1#" + encodeURIComponent(college.name),
			});

			const redirect_to = redirectPayload.toString();

			abbr = frappe.get_abbr(college.name);

			cardHTML = `
				<div class="card cursor-pointer p-5 h-100">
					<div class="d-flex flex-row">
						<div>
							<div class="mx-auto mb-3 rounded-circle text-white d-flex align-items-center display-4 justify-content-center" style="height: 70px; width: 70px; background-color: #badc95;">
								${abbr}
							</div>
						</div>
						<div class="col my-auto">
							<h5 class="card-title font-weight-bold">${college.name}</h5>

							<div class="d-flex flex-col">
								<img alt="Location Icon" class="feature-icon" src="/assets/bhumi_awards_portal/images/location.png">
								<span class="card-text d-block mb-4">${college.location}</span>
							</div>
						</div>
					</div>
					<div class="d-flex justify-content-between align-items-center card-footer mt-auto bg-transparent">
						<div class="d-flex flex-col">
							<img alt="Location Icon" class="feature-icon" src="/assets/bhumi_awards_portal/images/vote.png">
							<span class="m-0 mr-3 p-0 mr-1">
								${college.total_votes}
								${college.total_votes == 1 ? "vote" : "votes"}
							</span>
						</div>

						<div class="d-flex actions">
							<a href="/login?${redirect_to}" class="btn btn-sm btn-primary">Vote Now</a>

							<div class="webShareIcons ml-2">
								<a id="webShare" class="btn btn-sm btn-primary btn-social" onClick="share(this);" data-college="${college.name}" data-message-title="{{ social_media_title }}" data-message-text="{{ social_media_message }}">
									<img class="share-icon" src="/assets/bhumi_awards_portal/images/share.png">
								</a>
							</div>
							<div class="sharerUrlIcons ml-2">
								<div class="social-icons" id="s-icons">
									<a class="btn btn-primary btn-sm btn-social" id="btn-share" data-toggle="modal" data-target="#social_media_modal" data-college="${college.name}">
										<img class="share-icon" src="/assets/bhumi_awards_portal/images/share.png">
									</a>
								</div>
							</div>
						</div>
					</div>
				</div>
			`

			// Append this card to college listings
			const cardElement = document.createElement("div");
			cardElement.classList.add("col-lg-4", "col-sm-12", "col-md-6", "mb-4");
			cardElement.innerHTML = cardHTML;
			collegeListings.append(cardElement);
		}
	}

	function showShareButtons() {
		// share colleges
		if (navigator.share && frappe.is_mobile()) {
			document.querySelectorAll('.sharerUrlIcons').forEach(function(el) {
				el.style.display = 'none';
			});
		} else {
			document.querySelectorAll('.webShareIcons').forEach(function(el) {
				el.style.display = 'none';
			});
		}
	}

	function share(element) {
		if (navigator.share) {
			let college = element.getAttribute("data-college");
			let message = eval("`" + element.getAttribute("data-message-text") + "`");
			let title = eval("`" + element.getAttribute("data-message-title") + "`");
			message = message.replace("[object Object]", college);

			let url_param = get_url_param(college)

			navigator.share({
				title: title,
				text: message,
				url: url_param,
			})
			.then(() => console.log("Successfully shared"))
			.catch((error) => console.log("Error sharing", error));
		}
	}

	$("#social_media_modal").on("show.bs.modal", function(event) {
		let college = $(event.relatedTarget).data("college");
		let url_param = get_url_param(college);

		let message = eval("`" + $(this).find(".modal-body").data("message-text") + "`");
		let title = eval("`" + $(this).find(".modal-body").data("message-title") + "`");

		// Facebook
		let params = new URLSearchParams({
			"u": url_param,
			"quote": message
		});
		const fb_payload = params.toString();

		let fb_url = "https://www.facebook.com/sharer/sharer.php?" + fb_payload;
		$(this).find(".modal-body #fb").attr("onClick", `window.open('${fb_url}')`);

		// Twitter
		params = new URLSearchParams({
			"url": url_param,
			"text": message
		});
		const twitter_payload = params.toString();

		let twitter_url = "https://twitter.com/intent/tweet?" + twitter_payload;
		$(this).find(".modal-body #twitter").attr("onClick", `window.open('${twitter_url}')`);

		// Whatsapp
		message += "\n" + `Voting Link: ${url_param}`;
		params = new URLSearchParams({
			"text": message,
		});
		const whatsapp_payload = params.toString();

		let whatsapp_url = "https://wa.me/?" + whatsapp_payload;
		$(this).find(".modal-body #whatsapp").attr("onClick", `window.open('${whatsapp_url}')`);
	});

	function get_base_url() {
		let url = window.location.origin;
		if (url.substr(url.length-1, 1)=='/')
			url = url.substr(0, url.length-1);
		return url;
	}

	function get_url_param(college) {
		let url = get_base_url();
		const redirectPayload = new URLSearchParams({
			"redirect-to": "/vote?new=1#" + encodeURIComponent(college)
		});

		const redirect_to = redirectPayload.toString();
		return `${url}/login?${redirect_to}`;
	}

	function toggleLoadButton(visible = true) {
		loadMoreButton.style.display = visible ? "none" : "block";
	}

	function resetState() {
		for (let input of filterInputs) {
			filters[input.key] = input.ele.value;

			if (input.key === "sortBy") {
				filters.sortOrder =
					input.ele.value == "total_votes" ? "desc" : "asc";
			}
		}

		toggleLoadButton(false);
		collegeListings.innerHTML = "";
		pageStart = 0;
		pageLimit = 30;
	}

	// First load
	frappe.ready(() => loadNextPage());

	window.onscroll = function() {add_sticky_to_filter_area()};

	// Get the header
	var header = document.getElementById("filters-area");

	// Get the offset position of the navbar
	var sticky = header.offsetTop;

	// Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
	function add_sticky_to_filter_area() {
		if (window.pageYOffset > sticky) {
			header.classList.add("sticky", "container-fluid");
			header.classList.remove("container");
		} else {
			header.classList.add("container");
			header.classList.remove("sticky", "container-fluid");
		}
	}
</script>